﻿using HtmlAgilityPack;

using Newtonsoft.Json;

using RestSharp;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using ToChaoXing.Models;

using ToWangKe.Core;

using ToWangKeLib.Models;

namespace ToWangKeLib
{
    public class ChaoXing
    {
        public static List<RestResponseCookie> LoginCookies { get; set; } = new List<RestResponseCookie>();
        public static List<Parameter> LoginHeaders { get; set; } = new List<Parameter>();

        /// <summary>
        /// 登录超星网页版
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="pwd">密码</param>
        public static bool Login(string name, string pwd)
        {
            var clientLogin = new RestClient(@"http://passport2.chaoxing.com/fanyalogin");
            var requestLogin = new RestRequest(Method.POST);

            requestLogin.AddParameter("fid", -1);
            requestLogin.AddParameter("uname", name);
            requestLogin.AddParameter("password", EnDe.Base64Encode(pwd));
            requestLogin.AddParameter("refer", "http%3A%2F%2Fi.chaoxing.com");
            requestLogin.AddParameter("t", true);
            var responseLoginStatus = clientLogin.Execute(requestLogin);
            LoginCookies = responseLoginStatus.Cookies.ToList();//获取所有Cookies
            LoginHeaders = responseLoginStatus.Headers.ToList();//获取所有Headers

            string json = responseLoginStatus.Content;

            var loginStatus = JsonConvert.DeserializeObject<LoginStatus>(json);
            if (loginStatus != null)
            {
                if (loginStatus.status == true)
                {
                    var url = System.Web.HttpUtility.UrlDecode(loginStatus.url);//解密
                    var client = new RestClient($"{url}");
                    var request = new RestRequest(Method.GET);
                    LoginCookies.ForEach((cookie) =>
                    {
                        if (!cookie.Name.Equals("route"))
                        {
                            request.AddCookie(cookie.Name, cookie.Value);
                        }
                    });
                    request.AddHeader("Content-Type", "text/html;charset=UTF-8");

                    var response = client.Execute(request);

                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取当前课程列表  信息
        /// </summary>
        public static List<CourseInfo> GetCourseList()
        {
            List<CourseInfo> courseInfos = new List<CourseInfo>();
            string rndNum = RandomTools.RndNum(13);
            var client = new RestClient(@$"http://mooc2-ans.chaoxing.com/visit/courses/list?v={rndNum}&rss=1&start=0&size=500&catalogId=0&searchname=");
            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "text/html;charset=UTF-8");
            ChaoXing.LoginCookies.ForEach((cookie) =>
            {
                request.AddCookie(cookie.Name, cookie.Value);
            });
            var response = client.Execute(request);
            string html = response.Content;

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            //获取课程内容
            var mainContent = doc.DocumentNode.SelectSingleNode("//ul[@class='course-list']") ?? default;

            //获取课程列表
            var courses = mainContent?.SelectNodes("li[@class='course clearfix catalog_0  learnCourse']") ?? default;

            foreach (var item in courses)
            {
                var course_cover = item.SelectSingleNode("div[@class='course-cover']");

                string courseUrl = course_cover.SelectSingleNode("a").Attributes["href"].Value.Trim().Replace("http", "https");
                string clazzId = course_cover.SelectSingleNode("input[@class='clazzId']").Attributes["value"].Value;
                string courseId = course_cover.SelectSingleNode("input[@class='courseId']").Attributes["value"].Value;
                string role = course_cover.SelectSingleNode("input[@class='role']").Attributes["value"].Value;

                var course_info = item.SelectSingleNode("div[@class='course-info']");
                string courseName = course_info.SelectSingleNode("h3/a/span[@class='course-name overHidden2']").Attributes["title"].Value;
                string teacher = course_info.SelectSingleNode("p[@class='line2 color3']").Attributes["title"].Value;

                CourseInfo courseInfo = new CourseInfo()
                {
                    CourseId = courseId,
                    ClazzId = clazzId,
                    CourseName = courseName,
                    CourseUrl = courseUrl,
                    Role = role,
                    Teacher = teacher
                };
                courseInfos.Add(courseInfo);
            }
            return courseInfos;
        }

        public static List<WorkInfo> GetFinishCourse(string courseName, string url)
        {
            List<WorkInfo> workInfos = new List<WorkInfo>();

            var client = new RestClient(url);
            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "text/html;charset=UTF-8");
            ChaoXing.LoginCookies.ForEach((cookie) =>
            {
                request.AddCookie(cookie.Name, cookie.Value);
            });
            var response = client.Execute(request);
            string html = response.Content;

            //string html = url;

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            //获取作业内容
            var mainContent = doc.DocumentNode.SelectSingleNode("//div[@class='mark_table padTop60']");

            //获取题目列表
            var works = mainContent?.SelectNodes("div[@class='mark_item']") ?? default;
            foreach (var work in works)
            {
                var titles = work?.SelectNodes("div[@class='marBom60 questionLi']") ?? default;
                foreach (var title in titles)
                {
                    try
                    {
                        string id = Guid.NewGuid().ToString("N");
                        var ques = title.SelectSingleNode("h3").InnerText.Split(".");
                        string workQuestion = ques[1].Trim();
                        string workSelect = "";
                        string workAnswer = "";

                        if (workQuestion.Contains("单选") || workQuestion.Contains("多选") || workQuestion.Contains("判断"))
                        {
                            #region 选择题
                            try
                            {
                                workSelect = title.SelectSingleNode("ul").InnerText.Replace("\t", "").Trim().Replace("\r\n", ";");
                            }
                            catch { }
                            try
                            {
                                workAnswer = title.SelectSingleNode("div[@class='mark_answer']/div/span[@class='colorGreen marginRight40 fl']").InnerText.Trim();
                            }
                            catch { }
                            #endregion
                        }
                        else if (workQuestion.Contains("填空"))
                        {
                            #region 填空题
                            try
                            {
                                workAnswer = title.SelectSingleNode("div[@class='mark_answer']/div/dl[@class='mark_fill colorGreen']").InnerText.Trim().Replace(" ", "").Replace("\t", "").Replace("\r\n", ";");
                            }
                            catch { }
                            #endregion
                        }

                        WorkInfo workInfo = new WorkInfo()
                        {
                            Id = id,
                            WorkAnswer = workAnswer,
                            WorkQuestion = workQuestion,
                            WorkSelect = workSelect,
                            CourseName = courseName
                        };
                        workInfos.Add(workInfo);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.ToString());
                    }
                }
            }

            return workInfos;
        }

        public static List<WorkInfo> GetFinishCourse2(string courseName, string url)
        {
            List<WorkInfo> workInfos = new List<WorkInfo>();

            var client = new RestClient(url);
            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "text/html;charset=UTF-8");
            ChaoXing.LoginCookies.ForEach((cookie) =>
            {
                request.AddCookie(cookie.Name, cookie.Value);
            });
            var response = client.Execute(request);
            string html = response.Content;

            //string html = url;

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            //获取作业内容
            var mainContent = doc.DocumentNode.SelectSingleNode("//div[@class='ZyBottom']");

            //获取题目列表
            var works = mainContent?.SelectNodes("div[@class='TiMu']") ?? default;

            foreach (var work in works)
            {
                //获取题目
                var title = work?.SelectSingleNode("div[@class='Zy_TItle clearfix']/div[@class='clearfix']");
                //获取选择
                var selects = work?.SelectNodes("ul[@class='Zy_ulTop']/li[@class='clearfix']");
                if (selects == null)
                {
                    selects = work?.SelectNodes("div[@class='Zy_TItle clearfix']");
                }
                //获取答案

                var answser = work?.SelectSingleNode("div[@class='Py_tk']");
                if (answser == null)
                {
                    answser = work?.SelectSingleNode("div[@class='Py_answer clearfix']");
                }
                try
                {

                    string id = Guid.NewGuid().ToString("N");
                    var ques = title.SelectSingleNode("div").InnerText;
                    string workQuestion = ques.Trim();
                    string workSelect = "";
                    string workAnswer = "";

                    foreach (var item in selects)
                    {
                        var s2 = item.InnerText.Replace("\t", "").Trim();
                        workSelect += s2 + ";";
                    }
                    workSelect = workSelect.Replace(" ", "").Replace("\r\n", "");
                    workAnswer = answser.InnerText.Replace("\t", "").Replace(" ", "").Trim();

                    WorkInfo workInfo = new WorkInfo()
                    {
                        Id = id,
                        WorkAnswer = workAnswer,
                        WorkQuestion = workQuestion,
                        WorkSelect = workSelect,
                        CourseName = courseName
                    };
                    workInfos.Add(workInfo);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                }
            }
            return workInfos;
        }


        public static List<string> VideoUrlList = new List<string>();
        public static List<string> VideoNameList = new List<string>();
        public static Dictionary<string, string> Downloads = new Dictionary<string, string>();

        public static string[] GetBooksName()
        {
            string names = @"
清理eMS数据;
窗口布局与管理;
项目描述;
创建项目导入资源;
创建项目导入资源12;
创建复合零件、分配焊点到零件上;
操作的创建与设置;
工艺双胞胎的创建与设置;
工艺资源的设置;
创建ProcessSimulate研究;
PD项目的导出与导入;
PS项目的保存与打开;
PS软件介绍与视窗的操作;
坐标系的创建与操控;
C形焊枪演示;
创建C形焊枪;
创建X形焊枪1;
夹爪演示;
创建夹爪机构;
创建复合设备;
机器人本体模型;
机器人回转台机构模型;
安装机器人焊枪;
机器人导轨演示;
安装机器人导轨;
机器人回转台演示1;
安装回转台;
创建逻辑块;
传输带机构演示;
传输带机构的操作设计;
AGV小车演示;
准备文件与布局;
ACV小车的工具定义;
ACV小车的抓握操作;
让AGV小车沿轨迹移动;
创建物料流与仿真序列;
机运线机构演示;
创建机运线机构;
高架仓库演示;
高架仓库模型导入与零件建模;
高架仓库运动学建模;
编辑抓握机构;
高架仓库的LB逻辑块;
创建操作和LB逻辑块;
创建物料流和设置操作;
C形焊枪信号与参数演示;
逻辑块中的信号与参数;
复合设备LB信号与参数演示;
复合设备信号连接;
创建接近传感器;
创建光电传感器;
机器人工作站仿真演示;
准备文件与布局;
创建数控机床组件;
创建物流操作;
设置拾放操作;
设置抓取的过渡点;
CEE和物料流,干涉;
机器人信号设置;
机器人程序编辑;
模块编辑器和仿真效果;
创建PLC实例;
项目导人与调整;
建立逻辑块与事件;
建立操作中的事件;
PLC控制组态;
编写PLC程序;
虚拟调试系统运行;
创建机器人电弧焊工艺;
机器人电弧焊中变位机的使用;
变位机运动学编辑;
设置机器人外部轴;
可达范围测试;
创造制造特征NC代码文件1;
创造制造特征NC代码文件2;
机器人抛光演示;
机器人外部TCP抛光工艺操作;
机器人去毛刺演示;
机器人去毛刺工艺;
生成三维布局图;
生成动画图;
机器人铆焊演示;
创建PD项目;
建立工艺操作;
仿真环境布局与调整;
创建示教PS项目;
Process Simulate仿真操作;
干涉区设置;
焊点的切面;
研究创建项目与环境布局;
创建人体操作;
创建机器人拾放操作
";
            string[] nameArray = names.Split(";");
            return nameArray;
        }
        public static string GetVideoUrl(string url)
        {
            var client = new RestClient(url);
            var request = new RestRequest(Method.GET);
            request.AddHeader("Content-Type", "text/html;charset=UTF-8");
            //ChaoXing.LoginCookies.ForEach((cookie) =>
            //{
            //    request.AddCookie(cookie.Name, cookie.Value);
            //});
            var response = client.Execute(request);
            string html = response.Content;

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            //获取视频名称
            var mainContent = doc.DocumentNode.SelectSingleNode("//div[@class='main_box']");
            var eles = mainContent.SelectNodes("div[@class='video_info']/p");
            string[] names = eles[1].InnerText.Trim().Split("：");
            string name = names[1];
            VideoNameList.Add(name);
            //获取视频链接
            string[] strs = html.Split(',');
            string[] sources = strs[4].Trim().Replace("\r\n", "").Replace("\t", "").Replace("\"", "").Replace("\\", "").Split(":");
            string videoStr = (sources[1] + ":" + sources[2]).Trim();
            VideoUrlList.Add(videoStr);
            return videoStr;
        }

        /// <summary>
        /// 下载机械工业的视频资源
        /// </summary>
        /// <param name="pathUrl"></param>
        public static void DownLoad_Video(string pathUrl, string videoName, string index = "")
        {
            System.Net.HttpWebRequest request = null;
            System.Net.HttpWebResponse response = null;
            //请求网络路径地址
            request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pathUrl);
            request.Timeout = 5000; // 超时时间
                                    //获得请求结果
            response = (System.Net.HttpWebResponse)request.GetResponse();
            //文件下载地址
            string path = Directory.GetCurrentDirectory() + @"\video";

            // 如果不存在就创建file文件夹
            if (!Directory.Exists(path))
            {
                if (path != null) Directory.CreateDirectory(path);
            }
            path = path + $"/{index}-{videoName}.mp4";
            using (Stream stream = response.GetResponseStream())
            {
                using(Stream sos = new FileStream(path, FileMode.Create))
                {
                    byte[] bytes = new byte[1024];
                    int total = stream.Read(bytes, 0, bytes.Length);
                    while (total > 0)
                    {
                        sos.Write(bytes, 0, total);
                        total = stream.Read(bytes, 0, bytes.Length);
                    }
                    sos.Close();
                }
                stream.Close();
            }
            //Stream stream = response.GetResponseStream();
            ////先创建文件
            //Stream sos = new System.IO.FileStream(path, System.IO.FileMode.Create);
            //byte[] img = new byte[1024];
            //int total = stream.Read(img, 0, img.Length);
            //while (total > 0)
            //{
            //    //之后再输出内容
            //    sos.Write(img, 0, total);
            //    total = stream.Read(img, 0, img.Length);
            //}
            //stream.Close();
            //stream.Dispose();
            //sos.Close();
            //sos.Dispose();
        }
    }
}